﻿#判断是否是SpringBoot应用程序
#判断依据Pom文件中的spring-boot-starter-parent
#判断模式是否为检测模式 999
# $OutputEncoding = [System.Text.Encoding]::utf8
#命名规则 模版文件就用 T_(template)开头 F_表示文件 P_表示路径
# 项目文件命名规则 P_(Project) 开头 F_表示文件 P_表示路径
#举例 T_F_Test 就表示模版文件 Test TemplateFile-Test
$encoding = New-Object System.Text.UTF8Encoding($false)
$T_P_HOME=".temp\.template\SpringBootOpt\MyBatisPlus\SingleSystem\"
$T_F_Test=".\.temp\.template\SpringBootOpt\MybatisPlus\SingleSystem\test_.java"
$T_F_Controller=".\.temp\.template\SpringBootOpt\MybatisPlus\SingleSystem\controller_.java"
$T_F_ApplicationYml=($ProjectHome+$T_P_HOME+"\application.yml")
$T_F_ApplicationJava=($ProjectHome+$T_P_HOME+"\Application.java")
$T_F_ControllerReq=($ProjectHome+$T_P_HOME+"\ControllerReq.java")
$T_F_ControllerResp=($ProjectHome+$T_P_HOME+"\ControllerResp.java")
$T_F_DictDataController=($ProjectHome+$T_P_HOME+"\DictDataController_.java")
$T_F_DictTypeController=($ProjectHome+$T_P_HOME+"\DictTypeController_.java")
$T_F_AdminLoginController=($ProjectHome+$T_P_HOME+"\AdminLoginController_.java")
$T_P_Resources=".\.temp\src\main\resources"
$T_F_Converter=".temp\.template\SpringBootOpt\MyBatisPlus\SingleSystem\Converter_.java"

$P_P_Resources=".\src\main\resources"
$P_P_Yyge=".\src\main\java\com\yyge\"
$P_P_Main=".\src\main\"

$Pom=".\pom.xml"
$P_P_Entity=".\src\main\java\com\yyge\entity"
$P_P_Mapper=".\src\main\java\com\yyge\mapper"
$P_P_Controller=".\src\main\java\com\yyge\controller"
$P_P_Converter=".\src\main\java\com\yyge\controller\admin\mapstruct"
$P_P_XmlMapper=".\src\main\resources\mapper"
$P_P_Test=".\src\test\java\com\yyge\mapper\"
$P_F_Application=".\src\test\java\com\yyge\Application.java"

#缓存路径 CodeAutoGenerator 简称 CodeAG
$C_P_CodeAG= $env:USERPROFILE+"\AppData\Local\CodeAG"
$C_P_Data= $env:USERPROFILE+"\AppData\Local\CodeAG\.Data"
$C_F_User= $env:USERPROFILE+"\AppData\Local\CodeAG\.Data\user.data"
$AddPath= $env:USERPROFILE+"\AppData\Local\CodeAG\.Data\add\"


$APIPrefix=""
# 是否开启多端登录 (PC/Phone)
$MultiSystem=$false

#复制Application.java启动项
if(!(Test-Path -Path $P_F_Application)){
    if($Detection -ne $true){
      Copy-Item -Path $T_F_ApplicationJava -Destination $P_P_Yyge -Recurse -Force | Out-Null
    }
}


#   $T_F_ApplicationJava
#不存在则创建 以免Get-ChildItem报错 Test-Path
CreateDir($P_P_XmlMapper)
CreateDir($P_P_Test)#判断文件夹是否存在
CreateDir($C_P_CodeAG) #创建缓存目录用于存放Data
CreateDir($C_P_Data) #创建缓存目录用于存放Data

# 如果原来的$P_P_XmlMapper路径内没有文件 则重新赋值为".\src\main\resources\com\yyge\mapper\"
# if((Get-ChildItem $P_P_XmlMapper -File).Count -eq 0){
#     $P_P_XmlMapper=".\src\main\resources\com\yyge\mapper\"  
# }



if($Detection -ne $true){
    CreateDir($P_P_Yyge)
    CreateDir($P_P_Main)
    CreateDir($P_P_Entity) # 判断文件夹是否存在
    CreateDir($P_P_Mapper) # 判断文件夹是否存在
    CreateDir($P_P_Controller)
}


if(Test-Path -Path $AddPath){
  Remove-Item -Path $AddPath -Recurse -Force | Out-Null
}



Write-Host ("`n!!!正在自定义必要的设置....") -ForegroundColor Green 
$APIPrefix=Read-Host "==>请填写自定义API搜索接口的前缀,不需要设置直接按Enter键结束"

# 注入MybatisPlus
if($Detection -eq $false){
    $OPT=Read-Host "==>是否注入MybatisPlus相关依赖? 是(1)/否(2)"
    $Multi=Read-Host "==>是否生成开启多端后台(电脑/手机)? 是(1)/否(2)"
    if($Multi -eq 1){
      $MultiSystem = $true
    }
    if($OPT -eq 1){
            $SpringBoot=$true
            $SpringBootPomText=Get-Content -Encoding utf8 -Path $Pom -Raw
            #判断依据为报红问题是否引入
            if($SpringBootPomText.IndexOf("spring-boot-configuration-processor") -eq -1){
                if($SpringBootPomText.IndexOf("<parent>") -ne -1){
                    $SpringBootPomText=$SpringBootPomText -replace "<parent>","`n  <!--当前项目继承的依赖关系-->`n    <parent>"
                }
                if($SpringBootPomText.IndexOf("<groupId>com.yyge") -ne -1){
                    $SpringBootPomText=$SpringBootPomText -replace "<groupId>com.yyge","`n 	<!--项目的坐标以及打包方式-->`n    <groupId>com.yyge"
                }

                $PomTemplateText=Get-Content -Encoding utf8 -Path ($ProjectHome+".temp\.template\SpringBootOpt\MyBatisPlus\MybatisPlusPom_.xml") -Raw
                
                $ReplaceTxt=[Regex]::Split($SpringBootPomText, "</dependencies>")
                $TempText=""
                for ($i = 0; $i -lt $ReplaceTxt.Length; $i++) {
                  #判断是否为最后一个元素
                  if($i -ne ($ReplaceTxt.Length-1)){
                    if($ReplaceTxt[$i].IndexOf("<dependencyManagement>") -eq -1){
                        $TempText=($TempText+$ReplaceTxt[$i]+"</dependencies>") -replace "</dependencies>",($PomTemplateText+"`n")
                       }else{
                        $TempText=($TempText+$ReplaceTxt[$i]+"</dependencies>")
                       }
                  }else{
                    $TempText=($TempText+$ReplaceTxt[$i])
                  }
                }
                # 获取绝对路径
                $Pom=(Get-Item -Path $Pom).FullName
                [System.IO.File]::WriteAllLines($Pom,$TempText,$encoding)
            }

        #Spring项目
        #给pom.xml文件添加内容
        # if((Get-Content $Pom -Encoding utf8 -Raw).IndexOf("{spring.framework.version}") -eq -1){
        #     ReplaceTxt $Pom "</dependencies>" (Get-Content .\.temp\pom_.xml -Encoding utf8 -Raw)

        #     #添加版本信息 ${spring.framework.version}
        #     ReplaceTxt $Pom "</properties>" "<spring.framework.version>5.3.27</spring.framework.version>`n  </properties>"
        # }

    }
}

if($Detection -ne $true){
 CopyFile $T_P_HOME $P_P_Yyge
}


#判断是否为SpringBoot应用程序 如果是则复制配置文件到工程目录 并且是 非检测模式
if(($SpringBoot -eq $true) -and ($Detection -ne $true)){
  #当前是SpringBoot-MybatisPlus应用程序
  Copy-Item -Path $T_F_ApplicationYml -Destination $P_P_Resources -Force | Out-Null
}

if(($SpringBoot -ne $true) -and ($Detection -ne $true)){
    #复制resources资源目录
    Copy-Item -Path $T_P_Resources -Destination $P_P_Main -Recurse -Force | Out-Null
}


$TestFileBody=Get-Content -Encoding utf8 $T_F_Test -Raw

$Y_EntityName="temp"
$Data=@{}
#实例类名 list
$Global:Y_EntityNameList = @()

#数据库列名
$Global:BDColumnNameList = @()

#实体类属性
$Global:EntityNameList = @()

#数据库列的类型
$jdbcTypeList = @()

#数据库表名
$DBTableNameList = @()





# 临时备注
$NoteList= @()
$Noteverify= @()

# 全局备注
$Global:NoteListAll= @()
$Global:NoteverifyAll= @()

#删除EmployeeMapper.xml 如果存在的话
if(Test-Path -Path ".\src\main\resources\com\yyge\mapper\EmployeeMapper.xml"){
    if($Detection -ne $true){
     Remove-Item -Path ".\src\main\resources\com\yyge\mapper\EmployeeMapper.xml" -Force | Out-Null
    }
}


# 设置Controller的函数
<#
 @param $n 实体类名称
 @param $InfoList 实体类属性的注释数组
 @param $NameList 实体类属性的名称数组
 @param $TypeNameList 实体类属性的类型数组
#>
function CreateController($n,$InfoList,$NameList,$TypeNameList){
  # SysDictData
  # SysDictType
  # $m="SysDictData" #测试参数

  # 文件大写名称
  $Name=$n
 
  # 文件小写名称 连接Join " " 强制将对象转为字符串
  $Temp11 = Get-Replace "controller" $Name
  # $Temp11=$Temp11 -join " "
  # 赋值默认名称 比如字典默认名称等等
  $Name=Get-Name($Name)
  $LowerName=$Name.ToLower()

  if(($APIPrefix.Trim()).Length -ne 0){
    $Temp11=$Temp11 -replace "<---PREFIX--->",("(`""+$APIPrefix+"`")")
  }else{
    $Temp11=$Temp11 -replace "<---PREFIX--->",""
  }
  $Temp11=$Temp11 -replace "__.__",$Name.ToLower() 

  
  CreateDir($P_P_Controller+"\admin\"+$LowerName)
  CreateDir($P_P_Controller+"\admin\"+$LowerName+"\req")
  CreateDir($P_P_Controller+"\admin\"+$LowerName+"\resp")
  $Temp12=$P_P_Controller+"\admin\"+$LowerName+"\"+$Name+"Controller.java"
  
  # Read-Host ("路径:"+$Temp12)
  # 判断是否是检测模式
  if($Detection -ne $true){
    New-Item -ItemType File -Path $Temp12 -Value $Temp11 -Force | Out-Null
  }


  # 遍历实体类获取属性
  $TempReqText="" # 条件查询请求对象
  $TempAddReqText="" # 新增请求对象
  $TempEditReqText="" # 修改请求对象

  $TempRespText="" # 响应对象
  for ($i = 0; $i -lt $NameList.Length; $i++) {
    $Str=$NameList[$i]
   if(($Str.IndexOf("1L") -eq -1) -and ($Str.IndexOf("params") -eq -1)){
    $NoteReq="     /**`n      * "+$InfoList[$i]+"`n      */`n      @ApiModelProperty(value = `""+$InfoList[$i]+"`")`n"
    $NoteResp="     /**`n      * "+$InfoList[$i]+"`n      */`n"

    $TempReqText+=$NoteReq+"      private "+$TypeNameList[$i]+" "+$Str+";`n`n";

    # 修改请求对象 不含修改时间和修改人
    if($Str -notin @("updateTime","updateBy")){
      $TempEditReqText+=$NoteReq+"      private "+$TypeNameList[$i]+" "+$Str+";`n`n";
    }

    # 新增请求对象 不含创建时间、创建人、修改时间、修改人
    if($InfoList[$i] -ne "主键" -and $Str -notin @("updateTime","updateBy","createBy","createTime")){
      $TempAddReqText+=$NoteReq+"      private "+$TypeNameList[$i]+" "+$Str+";`n`n";
    }
    $TempRespText+=$NoteResp+"      private "+$TypeNameList[$i]+" "+$Str+";`n`n";
   }
  }

  $ReqText=Get-Replace (Get-Text $T_F_ControllerReq) $Name
  # $ReqText=$ReqText -join " "
  $ReqText=$ReqText -replace "<____AUTHOR____>","Gityyge"
  $ReqText=$ReqText -replace "<____DATE____>",((Get-Date).ToString())

  $ReqList=$TempReqText,$TempAddReqText,$TempEditReqText
  $ClassNameList="Req","AddReq","EditReq" # Req类的名称后缀
  $ReqDesc="条件查询请求对象","新增请求对象","修改请求对象" # Req类的描述
  $BaseControllerPath=$P_P_Controller+"\admin\"+$LowerName+"\req\$Name"


  function New-ControllerReq($Str,$Path){
    for ($i = 0; $i -lt $ReqList.Length; $i++) {
      $Text=$Str -replace "<---ATT--->",$ReqList[$i]
      $Text=$Text -replace "<---DESC--->",$ReqDesc[$i]
      $Text=$Text -replace "<---CLASS--->",($Name+$ClassNameList[$i])
      if($ReqList[$i].IndexOf("BigDecimal") -ne -1){
        $Text= $Text -replace "<---IMPORT--->","import java.math.BigDecimal;"
       }else{
        $Text= $Text -replace "<---IMPORT--->",""
      }
      New-Item -ItemType File -Path ($Path+$ClassNameList[$i]+".java") -Value  $Text -Force | Out-Null

    }
  }

  # 创建ControllerReq的类
  New-ControllerReq $ReqText $BaseControllerPath

  $ResqText=Get-Replace (Get-Text $T_F_ControllerResp) $Name
  # $ResqText=$ResqText -join " "
  $ResqText=$ResqText -replace "<____AUTHOR____>","Gityyge"
  $ResqText=$ResqText -replace "<____DATE____>",((Get-Date).ToString())
  $ResqText=$ResqText -replace "<---ATT--->",$TempRespText
  if($TempRespText.IndexOf("BigDecimal") -ne -1){
    $ResqText=$ResqText -replace "<---IMPORT--->","import java.math.BigDecimal;"
  }else{
    $ResqText=$ResqText -replace "<---IMPORT--->",""
  }

  # 创建Req
  $ResqPath=$P_P_Controller+"\admin\"+$LowerName+"\resp\$Name"+"Resp.java"
  New-Item -ItemType File -Path $ResqPath -Value $ResqText -Force | Out-Null
}

# 创建转换器 Converter
function CreateConverter($n){
 $ConverterText=Get-Content -Path $T_F_Converter -Encoding utf8 -Raw
 $ConverterText=$ConverterText -replace "<---ENTITYNAME--->",($n.ToLower())
 $ConverterText=$ConverterText -replace "_____",$n
 
 $ConverterFile=$P_P_Converter+"\$n"+"Converter.java"
 New-Item -ItemType File -Path $ConverterFile -Value $ConverterText -Force | Out-Null
}


# 登录检测
function UserCheck(){
  #登陆检测
  for ($i = 0; $i -lt $Global:Y_EntityNameList.Length; $i++) {
    $NameEntity=$Global:Y_EntityNameList[$i]
    # Write-Host (">_正在登陆检测 $NameEntity ...")
    #将数组转换为字符串 判断内容是否包含xxx,xxx
    $BDCountCol="" # DB账号列名
    $BDPassCol="" # DB密码列名
    $BDIDCol="" # DBID列名
    $BDNameCol="" # DB昵称列名
    $BDAvatarCol="" # DB头像地址列名
    $BDStatusCol="" # DB状态列名
    $BDTypeCol="" # DB类型列名


    $EnCountAtt="" # 实体类账号属性名
    $EnPassAtt="" # 实体类密码属性名
    $EnIDAtt="" # 实体类ID属性名
    $EnNameAtt="" # 实体类昵称属性名
    $EnAvatarAtt="" # 实体类头像地址属性名
    $EnStatusAtt="" # 实体类状态属性名
    $EnTypeAtt="" # 实体类类型属性名

    #声明二维数组用于存放登录的信息 实体类的类名 账号属性名、密码属性名
    #_T 临时存放 在循环后加入主文件 由此得到二维数组,LoginEntityName存放的是实体类的类名所以他不存在二维数组直接存放即可
    $LoginEntityName_T,$LogInEntiCount_T,$LogInEntiPass_T=@(),@(),@()
    $LoginEntityID_T,$LogInEntiNickName_T,$LogInEntiAvatar_T=@(),@(),@()
    $LoginEntityStatus_T,$LogInEntiType_T=@(),@()
    $NoteStr = $Global:NoteListAll[$i] -join ","
    $LoginPass = -1 
    # 判断依据就是有账号&密码
    if(($NoteStr.IndexOf("账号") -ne -1) -or ($NoteStr.IndexOf("账户") -ne -1)){
      if($NoteStr.IndexOf("密码") -ne -1){
        $LoginPass=1
      }
    }
    if($LoginPass -eq 1){
      # 用户ID
      # 昵称
      # 登陆账户
      # 登陆密码
      # 头像地址
      # 用户状态
      # 用户类型

        for ($j = 0; $j -lt $Global:NoteListAll[$i].Length; $j++) {
            $V=$Global:NoteListAll[$i][$j]
            if(($V -eq "账号") -or ($V -eq "账户")){
                $EnCountAtt=$Global:EntityNameList[$i][$j]
                $BDCountCol=$Global:BDColumnNameList[$i][$j]
            }
            if($V -eq "密码"){
                $EnPassAtt=$Global:EntityNameList[$i][$j]
                $BDPassCol=$Global:BDColumnNameList[$i][$j]
            }
            if($V -eq "ID"){
                $EnIDAtt=$Global:EntityNameList[$i][$j]
                $BDIDCol=$Global:BDColumnNameList[$i][$j]
            }

            if($V -eq "昵称"){
                $EnNameAtt=$Global:EntityNameList[$i][$j]
                $BDNameCol=$Global:BDColumnNameList[$i][$j]
            }

            if($V.IndexOf("头像") -ne -1){
                $EnAvatarAtt=$Global:EntityNameList[$i][$j]
                $BDAvatarCol=$Global:BDColumnNameList[$i][$j]
            }
            if($V.IndexOf("状态") -ne -1){
                $EnStatusAtt=$Global:EntityNameList[$i][$j]
                $BDStatusCol=$Global:BDColumnNameList[$i][$j]
            }
            if($V.IndexOf("类型") -ne -1){
                $EnTypeAtt=$Global:EntityNameList[$i][$j]
                $BDTypeCol=$Global:BDColumnNameList[$i][$j]
            }
        }
    }

    if($BDCountCol -ne ""){
        # 先检查本地文件是否存在User
        $UserData=$C_P_CodeAG+"\.data\user.data"
        IF(Test-Path -Path $UserData){
          $Str = Get-Content -Encoding utf8 -Path $UserData -Raw
          $UserObj=ConvertFrom-Json $Str
          # 赋值操作
          $UserName = $UserObj.LogInEntiCount
          $Password = $UserObj.LogInEntiPass
          $EntityName = $UserObj.entityName
          if($EntityName -eq $Global:Y_EntityNameList[$i]){
            return;
          }
        }
        $Str_1="  检测到 "+ $Global:Y_EntityNameList[$i]+" 实体类似乎需要登陆功能..."
        $Str_2="  ----> 账号属性: "+$EnCountAtt
        $Str_3="  ----> 密码属性: "+$EnPassAtt
        $Str_4="  ----> ID属性: "+$EnIDAtt
        $Str_5="  ----> 昵称属性: "+$EnNameAtt
        $Str_6="  ----> 头像属性: "+$EnAvatarAtt
        $Str_7="  ----> 状态属性: "+$EnStatusAtt
        $Str_8="  ----> 类型属性: "+$EnTypeAtt
        Write-Host ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" -ForegroundColor Blue 
        Write-Host $Str_1 -ForegroundColor Blue 
        Write-Host $Str_2 -ForegroundColor Blue 
        Write-Host $Str_3 -ForegroundColor Blue 
        Write-Host $Str_4 -ForegroundColor Blue 
        Write-Host $Str_5 -ForegroundColor Blue 
        Write-Host $Str_6 -ForegroundColor Blue 
        Write-Host $Str_7 -ForegroundColor Blue 
        Write-Host $Str_8 -ForegroundColor Blue 
        Write-Host ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" -ForegroundColor Blue 
        $InputNum=Read-Host "  是否需要加入登陆功能？是(1)/否(2)"
        if($InputNum -eq 1){
        #   $LogTextPath=$P_P_XmlMapper+$Y_EntityNameList[$i]+"Mapper.xml"
        #   $Text1="<select id=`"login`" resultMap=`"BaseResultMap`">`n"
        #   $Text1=$Text1+"        select`n"+"             <include refid=`"Base_Column_List`" />`n"+"       from "+$DBTableNameList[$i]+"`n           where "+$BDCountCol+" = #{"+$EnCountAtt+"} and "+$BDPassCol+" = #{"+$EnPassAtt+"}`n"+"    </select>`n"
        #   $XmlTextBody=(Get-Content -Encoding utf8  $LogTextPath -Raw) -replace ("<select id=`"login`" resultMap=`"BaseResultMap`"/>"),$Text1
        #   [System.IO.File]::WriteAllLines($LogTextPath,$XmlTextBody,$encoding)
          
          #将Test.java中的@Login进行替换
          $TestPath=$P_P_Test+"\"+$Global:Y_EntityNameList[$i]+"MapperTest.java"
          $ToUpperCount=($EnCountAtt.Substring(0,1).ToUpper()+$EnCountAtt.Substring(1))
          $ToUpperPass=($EnPassAtt.Substring(0,1).ToUpper()+$EnPassAtt.Substring(1))
          $Text2="@Test`n    public void login(){`n        _____Service service=new _____ServiceImpl();`n        _____ user=new _____();`n"
          $Text2=$Text2+"        user.set"+$ToUpperCount+"(`"xxxxxxxxxx`");`n        user.set"+$ToUpperPass+"(`"xxxxxxxxxx`");`n        //设置对象的账号和密码`n        R r =service.login(user);`n        System.out.println(r.getData());`n    }"
          $Text2=$Text2 -replace "_____",$Global:Y_EntityNameList[$i]
          $TestBody=(Get-Content -Encoding utf8  $TestPath -Raw) -replace "@Login",$Text2
          
          [System.IO.File]::WriteAllLines(((Get-Item -Path $TestPath).FullName),$TestBody,$encoding)

          #将关键数据传入临时的数组 登录实体类的账号、密码属性 
          $LogInEntiCount_T+=$EnCountAtt
          $LogInEntiPass_T+=$EnPassAtt
          $LogInEntiID_T+=$EnIDAtt
          $LogInEntiNickName_T+=$EnNameAtt
          $LogInEntiAvatar_T+=$EnAvatarAtt
          $LogInEntiStatus_T+=$EnStatusAtt
          $LogInEntiType_T+=$EnTypeAtt
          $LoginEntityName_T+=$Global:Y_EntityNameList[$i]
        }else{
            #如果用户选择了"否" 则会直接将Test.java中的@Login删除
            $TestPath=$P_P_Test+"\"+$Global:Y_EntityNameList[$i]+"MapperTest.java"  
            $TestBody=(Get-Content -Encoding utf8  $TestPath -Raw) -replace "@Login",""
            [System.IO.File]::WriteAllLines((Get-Item -Path $TestPath).FullName,$TestBody,$encoding)
        }
    }else{
        #如果当前实体类没有登陆项 则会直接将Test.java中的@Login删除
        $TestPath=$P_P_Test+"\"+$Global:Y_EntityNameList[$i]+"MapperTest.java"  
        if(Test-Path -Path $TestPath){
          $TestBody=(Get-Content -Encoding utf8  $TestPath -Raw) -replace "@Login",""
          [System.IO.File]::WriteAllLines((Get-Item -Path $TestPath).FullName,$TestBody,$encoding)
        }

    }

    if($LogInEntiCount_T.Length -gt 0){
      $UserData=@{}
      $UserDataBody=""
      $UserDataObject=@{}

      #取读user文件的内容
      if(Test-Path -path ".\.data\user.data"){
        $UserDataBody=Get-Content -Path ".\.data\user.data" -Encoding utf8 -Raw
      }

      
      Write-Host ("正在准备判断 UserDataBody:"+($UserDataBody.Length))
      $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
      if(($UserDataBody.Length) -ne 0){
        Write-Host ("我来了")
        $ObjectUser=@{}
        $UserDataObject=ConvertFrom-Json $UserDataBody
        Write-Host $UserDataObject
        $Arr_1=@()
        $Arr_1+=$UserDataObject["entityName"]
        $Arr_1+=$Global:Y_EntityNameList[$i]
        $ObjectUser.Add("entityName",$Arr_1)

        $Arr_2=@()
        $Arr_2+=,$UserDataObject["LogInEntiCount"]
        $Arr_2+=,$LogInEntiCount_T
        $ObjectUser.Add("LogInEntiCount",$Arr_2)

        $Arr_3=@()
        $Arr_3+=,$UserDataObject["LogInEntiPass"]
        $Arr_3+=,$LogInEntiPass_T
        $ObjectUser.Add("LogInEntiPass",$Arr_3)

        $Arr_4=@()
        $Arr_4+=,$UserDataObject["LogInEntiId"]
        $Arr_4+=,$LogInEntiId_T
        $ObjectUser.Add("LogInEntiId",$Arr_4)

        $Arr_5=@()
        $Arr_5+=,$UserDataObject["LogInEntiName"]
        $Arr_5+=,$LogInEntiNickName_T
        $ObjectUser.Add("LogInEntiName",$Arr_5)
        
        $Arr_6=@()
        $Arr_6+=,$UserDataObject["LogInEntiAvatar"]
        $Arr_6+=,$LogInEntiAvatar_T
        $ObjectUser.Add("LogInEntiAvatar",$Arr_6)

        $Arr_7=@()
        $Arr_7+=,$UserDataObject["LogInEntiStatus"]
        $Arr_7+=,$LogInEntiStatus_T
        $ObjectUser.Add("LogInEntiStatus",$Arr_7)

        $Arr_8=@()
        $Arr_8+=,$UserDataObject["LogInEntiType"]
        $Arr_8+=,$LogInEntiType_T
        $ObjectUser.Add("LogInEntiType",$Arr_8)

      }else{
        $ObjectUser=@{}
        $ObjectUser.Add("entityName",$Global:Y_EntityNameList[$i])

        $ObjectUser.Add("LogInEntiCount",$LogInEntiCount_T)
        $ObjectUser.Add("LogInEntiPass",$LogInEntiPass_T)
        $ObjectUser.Add("LogInEntiID",$LogInEntiID_T)
        $ObjectUser.Add("LogInEntiName",$LogInEntiName_T)
        $ObjectUser.Add("LogInEntiAvatar",$LogInEntiAvatar_T)
        $ObjectUser.Add("LogInEntiStatus",$LogInEntiStatus_T)
        $ObjectUser.Add("LogInEntiType",$LogInEntiType_T)

        Write-Host ("查看临时LogInEntiCount=="+$LogInEntiCount_T)
        Write-Host ("查看临时LogInEntiPass=="+$LogInEntiPass_T)
        $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
        
      }

      $DataJson=$ObjectUser | ConvertTo-Json -Compress

        #临时存储登陆功能对应的entity名Get-Content
        $FilePath=(Get-Item -Path ".\.Data\user.data").FullName  
        
        New-Item -ItemType File -Path $FilePath -Force | Out-Null
        [System.IO.File]::WriteAllLines($FilePath,$DataJson,$encoding)

        $C_F_User=$C_P_CodeAG+"\.data\user.data"
        New-Item -ItemType File -Path $C_F_User -Force | Out-Null
        [System.IO.File]::WriteAllLines($C_F_User,$DataJson,$encoding)

        # Set-Content -Encoding $encoding -Path ".\.data\user.data" -Force -Value  $DataJson | Out-Null
    }
  }
}


# 写入数据(缓存)
function Set-Data(){
  Write-Host "基础data日志...."
  Write-Host "EntityNameList:"
  # 解决打印对象的问题System.Object[]
  $Var1=$Global:EntityNameList | Out-String
  # Write-Host $Var1

  Write-Host "BDColumnNameList:"
  # 解决打印对象的问题System.Object[]
  $Var2=$Global:BDColumnNameList| Out-String
  # Write-Host $Var2

  Write-Host "jdbcTypeList:"
  # 解决打印对象的问题System.Object[]
  $Var3=$jdbcTypeList| Out-String
  # Write-Host $Var3





  # 屏蔽之后就重新赋值
  $Global:NoteListAll+=,$NoteList[0]
  $Global:NoteverifyAll+=,$Noteverify[0]

  # for ($i = 0; $i -lt $EntityNameList.Length; $i++) {
  #     $V=@()
  #     $L=@()
  #     Write-Host ($NoteList[$i]) -ForegroundColor Red
  #     Write-Host ($Noteverify[$i]) -ForegroundColor Red

  #     if($NoteList[$i].Length -ne 0){
  #     for ($j = 0; $j -lt $EntityNameList[$i].Length; $j++) {
  #       if($j -lt $Noteverify[$i].Length){
  #         if($EntityNameList[$i][$j] -eq $Noteverify[$i][$j]){
  #             $V+=$Noteverify[$i][$j]
  #             $L+=$NoteList[$i][$j]
  #         }
  #       }else{
  #         $V+="*"
  #         $L+="*"
  #       }
  #     }

  #     }


  #   # if($EntityNameList[$i].Length -eq 0){
  #   #   Write-Host "EntityNameList 的长度等于0"
  #   #   $Noteverify_T+=,$Noteverify
  #   #   $NoteList_T+=,$NoteList
  #   # }else{
  #     $Noteverify_T+=,$V
  #     $NoteList_T+=,$L
  #   # }

  # }


  # Write-Host ("NoteListAll:"+$Global:NoteListAll) -ForegroundColor Red
  # Write-Host ("NoteverifyAll:"+$Global:NoteverifyAll) -ForegroundColor Red

  
  # Data转Json 只有基础的Data内容
  Write-Host "准备Add................."
  # Write-Host $Global:Y_EntityNameList
  # Write-Host $Global:BDColumnNameList
  # 重新赋值这个Data
  $Data=@{}
  $Data.Add("Y_EntityNameList", $Global:Y_EntityNameList)
  $Data.Add("BDColumnNameList", $Global:BDColumnNameList)
  $Data.Add("EntityNameList", $Global:EntityNameList)
  $Data.Add("jdbcTypeList", $jdbcTypeList)
  $Data.Add("DBTableNameList", $DBTableNameList)
  $Data.Add("NoteList", $Global:NoteListAll)
  $Data.Add("Noteverify", $Global:NoteverifyAll)
  
  $DataJson=$Data | ConvertTo-Json -Compress
  
  #声明二维数组用于存放登录的信息 实体类的类名 账号属性名、密码属性名
  $LoginEntityName,$LogInEntiCount,$LogInEntiPass=@(),@(),@()
  
  
  
  
  # 创建配置文件
  # $DataFile="./.temp/.data/config.data"
  # $DataFile_FN=(Get-Item -Path $DataFile).FullName
  # New-Item -ItemType File -Path $DataFile_FN -Force | Out-Null
  # [System.IO.File]::WriteAllLines($DataFile_FN,$DataJson,$encoding)
  
  #写入缓存User Cach
  $UserCachePath= $C_P_CodeAG+"\.Data\config.data"
  New-Item -ItemType File -Path $UserCachePath -Force | Out-Null
  [System.IO.File]::WriteAllLines($UserCachePath,$DataJson,$encoding)

  # 登录检测
  UserCheck

}



# 创建相关文件的函数
<#
 参数1：EntityName 实体类名称
 参数2：EntityFullName 实体类全路径
 参数3：Is 是否提示


#>
function CreateAll($EntityFullName,$Is){
  # 将文件全路径转化为名称
  $EntityName=(Get-Item -Path $EntityFullName).Name
  Write-Host "你来调用CreateAll了"
  if($EntityName.Contains("Mapper.java")){
    $Name=($EntityName -replace  "Mapper.java","")
    $Global:Y_EntityNameList += $Name
    if($Name -ne "Base"){
        $autoInt=-1
        #判断不为检测模式
        if($Detection -ne $true){
          $Path=".\src\main\java\com\yyge\controller\admin\"+($Name.ToLower())
          Write-Host "你来调用CreateAll了--监测点1"
          if(!(Test-Path -Path $Path)){
            # 如果没有controller 的话就会创建

            #$Is 是否提示 $Is为布尔值 true为提示
            if($Is){
              $autoInt=Read-Host ("是否自动创建 "+$Name+" 实体类相关后端文件?"+" 是(1)/否(2)")
              Write-Host ("`n-->>"+$Name+" 实体类正在创建...") -ForegroundColor Green  
            }else{
              $autoInt=1
              Write-Host "你来调用CreateAll了--监测点2"
            }

          }
         }else{
            Write-Host ("`n-->>"+$Name+" 实体类扫描开始") -ForegroundColor Green   
        }

        if(($autoInt -eq 1) -or ($Detection -eq $true)){
          Write-Host "你来调用CreateAll了--监测点3"
            #替换Entity文件内容--改造entity
            
            $P_F_Entity=(Get-Item -Path ($P_P_Entity+"\"+($Name)+".java")).FullName
            # Get-Item -Path $P_F_Entity
            
            $EntityFileBody=Get-Content -Encoding utf8 $P_F_Entity -Raw


            #给entity添加上集合 并且导入集合类 import java.util.Map;
            $EntityFileBody2=Get-Content -Encoding utf8 $P_F_Entity -Raw
            if($EntityFileBody2.IndexOf("private Map<String, Object> params;") -eq -1){
            $EntityFileBody=$EntityFileBody2 -replace "private static final long serialVersionUID = 1L;","private Map<String, Object> params;`n    private static final long serialVersionUID = 1L;`n"
            $EntityFileBody=$EntityFileBody -replace "import java.io.Serializable;","import java.io.Serializable;`nimport java.util.Map;"
            if($Detection -ne $true){
              [System.IO.File]::WriteAllLines($P_F_Entity, $EntityFileBody,$encoding)
            }
            }
            Write-Host "你来调用CreateAll了--监测点4"
            $P_F_Mapper_T=Get-Content -Encoding utf8 -Path $EntityFullName -Raw


            #给Mapper文件添加上@Mapper的注解
            if(($Detection -ne $true) -and ($P_F_Mapper_T.IndexOf("@Mapper") -eq -1)){
               Write-Host "你来调用CreateAll了--监测点4.0"
                $P_F_Mapper_T=$P_F_Mapper_T -replace "public interface","@Mapper`npublic interface"
                $P_F_Mapper_T=$P_F_Mapper_T -replace "import com.baomidou.mybatisplus.core.mapper.BaseMapper;","import com.baomidou.mybatisplus.core.mapper.BaseMapper;`nimport org.apache.ibatis.annotations.Mapper;"
                [System.IO.File]::WriteAllLines($EntityFullName, $P_F_Mapper_T,$encoding)
              }

            $Y_EntityName = $Name
            Write-Host "你来调用CreateAll了--监测点4.1"

            #提取含有备注的列
            $P_F_Entity=$P_P_Entity+"\"+($Name)+".java"
            Write-Host ("你来调用CreateAll了--监测点4.2"+$P_F_Entity)
            #临时数组用于存储 列的备注以及验证信息-- 
            $Note_TempList = setColumInfo $P_F_Entity

            # # 判断是否删除 1L和params
            # if(($Note_TempList[1].Length-1) -eq "1L"){
            #   $ArrLength=$Note_TempList[0].Length-1
            #   $Note_TempList[0] = $Note_TempList[0] | Where-Object {$_ -ne $Note_TempList[0][$ArrLength]}
            #   $Note_TempList[1]  = $Note_TempList[1] | Where-Object {$_ -ne $Note_TempList[1][$ArrLength]}

            # }

            # if(($Note_TempList[1].Length-1) -eq "params"){
            #   $ArrLength=$Note_TempList[0].Length-1
            #   $Note_TempList[0] | Where-Object {$_ -ne $Note_TempList[0][$ArrLength]}
            #   $Note_TempList[1] | Where-Object {$_ -ne $Note_TempList[1][$ArrLength]}
            # }

            # 全局对象赋值
            $NoteList+=,$Note_TempList[0]
            $Noteverify+=,$Note_TempList[1]

            # Write-Host "查看备注----||||||||||||||"
            # Write-Host $NoteList
            # Write-Host $Noteverify
            $DBTableNameList+=$Note_TempList[2]
            $AttTypeList+=$Note_TempList[3]

            # $StringOb=$NoteList | Out-String
            Write-Host ("你来调用CreateAll了--监测点4.3")
            # Read-Host $Note_TempList[0]
            # Read-Host $Note_TempList[1]
            
            Write-Host "你来调用CreateAll了--监测点5"
            # 设置Controller
            CreateController $Name $Note_TempList[0] $Note_TempList[1] $Note_TempList[3]

            # 设置Converter
            CreateConverter $Name

            #创建测试-全查selectAll
            Write-Host "你来调用CreateAll了--监测点6"
            $Temp9=$TestFileBody -replace "_____",$Name
            $Temp10=$P_P_Test+"\"+($Name)+"MapperTest.java"
            if($Detection -ne $true){
             New-Item -ItemType File -Path $Temp10 -Value $Temp9 -Force | Out-Null
             Write-Host ("-->>"+$Name+" 实体类相关后端文件已成功创建`n") -ForegroundColor Green
            }else{
                Write-Host ("-->>"+$Name+" 实体类已扫描完毕`n") -ForegroundColor Green   
            }
        }
    }
  }

  # 扫描Mapper的Xml
  if(Test-Path -Path $P_P_XmlMapper){
    Get-ChildItem -Path $P_P_XmlMapper -Recurse | ForEach-Object {
        if (!$_.PSIsContainer) {
            $DBTableName=""
            # 如果是文件而不是文件夹，则调用提供的函数对文件内容进行替换操作
            #(Get-Content $_.FullName) | Set-Content -Encoding $encoding $_.FullName
            if($_.Name.Contains("Mapper.xml") -and ($_.Name -ne "BaseMapper.java")){
                $bodyTxt =Get-Content $_.FullName -Encoding utf8 -Raw
                $words = [Regex]::Split($bodyTxt,"`r`n+")
                
                #数据库 列名
                $BDColumnName = @()
                #实体类属性
                $EntityName = @()
                #数据库列的类型
                $jdbcType = @()

                $Temp_sub=0
                foreach ($word in $words) {
                    if($word.IndexOf("BaseResultMap") -ne -1){$Temp_sub=1 }
                    if($Temp_sub -eq 1 -and $word.IndexOf("jdbcType=`"") -gt -1){
                        $ReplaceTxt=[Regex]::Split($word, "`"")
                        $BD_N_N = $ReplaceTxt[3].Trim()
                        $EN_N_N=$ReplaceTxt[1].Trim()

                        $EntityName += $EN_N_N
                        $BDColumnName += $BD_N_N
                        
                        $TY_N_N=$ReplaceTxt[5].Trim()
                        $jdbcType += $TY_N_N
                    }
                }

                # #如下代码嵌套为二维数组
                # $DBTableNameList += $DBTableName
                $Global:BDColumnNameList += ,$BDColumnName
                #实体类属性
                $Global:EntityNameList += ,$EntityName
                #数据库列的类型
                $jdbcTypeList += ,$jdbcType

            }
        }
    }
  }

  Set-Data
}
# 声明为全局函数
$Global:CreateAll = ${function:CreateAll}



Get-ChildItem -Path $P_P_Mapper -Recurse | ForEach-Object {
    if (!$_.PSIsContainer) {
        # 列备注 
        # 如果是文件而不是文件夹，则调用提供的函数对文件内容进行替换操作
        #(Get-Content $_.FullName) | Set-Content -Encoding $encoding $_.FullName
        &$Global:CreateAll $_.FullName $true
    }
}


# $ChildFile=Get-ChildItem -Path $P_P_XmlMapper

#删除EmployeeMapper.xml
if(Test-Path -path ".\src\main\java\com\yyge\web\servlet\IndexServlet.java"){
    if($Detection -ne $true){
      Remove-Item -Path ".\src\main\java\com\yyge\web\servlet\IndexServlet.java"
    }
}


#在项目目录中创建一个名为.data的目录
# $ProjectDataPath="./.data/"
# CreateDir($ProjectDataPath)
# #在项目目录中创建一个config.data的文件记录所有data数据
# $ProjectDataFile="./.data/config.data"
# $ProjectDataFile_FN=(Get-Item -Path $ProjectDataFile).FullName
# New-Item -ItemType File -Path $ProjectDataFile_FN -Force | Out-Null
# [System.IO.File]::WriteAllLines($ProjectDataFile_FN,$DataJson,$encoding)


#controller主键替换
# for ($i = 0; $i -lt $Y_EntityNameList.Length; $i++) {
#     $P_F_Controller=$P_P_Controller+"\"+$Y_EntityNameList[$i]+"Controller.java"
#     $Str_4="get"+($EntityNameList[$i][0].Substring(0,1).ToUpper()+$EntityNameList[$i][0].Substring(1))
#     $ControllerBody=(Get-Content -Encoding utf8 -Path $P_F_Controller -Raw) -replace "getId",$Str_4
#     $P_F_Controller_FN=(Get-Item -Path $P_F_Controller).FullName
#     [System.IO.File]::WriteAllLines($P_F_Controller_FN,$ControllerBody,$encoding)
# }




# 首字母转大写
function StrOneToUpper($Str) {
  if($Str){
    return ($Str.Substring(0,1).ToUpper() + $Str.Substring(1))
  }else{
    return ""
  }
  
}

# 首字母转小写
function StrOneToLower($Str) {
  if($Str){
    return ($Str.Substring(0,1).ToLower() + $Str.Substring(1))
  }else{
    return ""
  }
  
}

if(Test-Path -Path $C_F_User){
  $C_F_UserText=Get-Content -Encoding utf8 -Path $C_F_User -Raw

  $UserData=ConvertFrom-Json $C_F_UserText
  $P_F_LoginController=".\src\main\java\com\yyge\controller\LoginController.java"
  $LoginCtrollerText=Get-Content -Path  $P_F_LoginController -Encoding utf8 -Raw

  # 赋值Data数据
  $User_EntityName=$UserData.entityName
  $User_LogInEntiCount=$UserData.LogInEntiCount[1]
  $User_LogInEntiPass=$UserData.LogInEntiPass[1]
  $User_LogInEntiId=$UserData.LogInEntiId[1]
  if($UserData.LogInEntiName){
    $User_LogInEntiName=$UserData.LogInEntiName[1]
  }else{
    $User_LogInEntiName=""
  }
  
  $User_LogInEntiAvatar=$UserData.LogInEntiAvatar[1]
  $User_LogInEntiType=$UserData.LogInEntiType[1]

  Read-Host ("User_EntityName:$User_EntityName")
  Read-Host ("User_LogInEntiCount:$User_LogInEntiCount")
  Read-Host ("User_LogInEntiPass:$User_LogInEntiPass")
  Read-Host ("User_LogInEntiId:$User_LogInEntiId")
  Read-Host ("User_LogInEntiName:$User_LogInEntiName")
  Read-Host ("User_LogInEntiAvatar:$User_LogInEntiAvatar")
  Read-Host ("User_LogInEntiType:$User_LogInEntiType")
  
  $LoginCtrollerText = $LoginCtrollerText -replace "_____",(StrOneToUpper $User_EntityName)
  $LoginCtrollerText = $LoginCtrollerText -replace "__.MinName.__",(StrOneToLower $User_EntityName)
  $LoginCtrollerText = $LoginCtrollerText -replace "__.PwdName.__",(StrOneToUpper $User_LogInEntiPass)
  $LoginCtrollerText = $LoginCtrollerText -replace "__.LoginName.__",(StrOneToUpper $User_LogInEntiCount)

  $LoginUserStr="AdminLoginResp loginUser = new AdminLoginResp();`n"
  if($User_LogInEntiId){
    if($User_LogInEntiId.Trim() -ne ""){
      $LoginUserStr=$LoginUserStr+"       loginUser.setId(Integer.parseInt("+(StrOneToLower $User_EntityName)+".get"+(StrOneToUpper $User_LogInEntiId)+"()+`"`"));`n"
    }
  }

  if($User_LogInEntiName){
    if($User_LogInEntiName.Trim() -ne ""){
      $LoginUserStr=$LoginUserStr+"       loginUser.setName("+(StrOneToLower $User_EntityName)+".get"+(StrOneToUpper $User_LogInEntiName)+"());`n"
    }
  }

  if($User_LogInEntiCount){
    if($User_LogInEntiCount.Trim() -ne ""){
      $LoginUserStr=$LoginUserStr+"       loginUser.setLoginName("+(StrOneToLower $User_EntityName)+".get"+(StrOneToUpper $User_LogInEntiCount)+"());`n"
    }
  }

  if($User_LogInEntiPass){
    if($User_LogInEntiPass.Trim() -ne ""){
      $LoginUserStr=$LoginUserStr+"       loginUser.setLoginPwd("+(StrOneToLower $User_EntityName)+".get"+(StrOneToUpper $User_LogInEntiPass)+"());`n"
    }
  }

  if($User_LogInEntiAvatar){
    if($User_LogInEntiAvatar.Trim() -ne ""){
      $LoginUserStr=$LoginUserStr+"       loginUser.setAvatar("+(StrOneToLower $User_EntityName)+".get"+(StrOneToUpper $User_LogInEntiAvatar)+"());`n"
    }
  }

  if($User_LogInEntiType){
    if($User_LogInEntiType.Trim() -ne ""){
      $LoginUserStr=$LoginUserStr+"       loginUser.setAccountType("+(StrOneToLower $User_EntityName)+".get"+(StrOneToUpper $User_LogInEntiType)+"());`n"
    }
  }

  $LoginCtrollerText = $LoginCtrollerText -replace "<---LoginUser--->",$LoginUserStr

  # 获取全路径
  $LoginControllerPath = (Get-Item -Path $P_F_LoginController).FullName
  [System.IO.File]::WriteAllLines($LoginControllerPath,$LoginCtrollerText,$encoding)



  # 编写AdminLoginController_.java
  $AdminLoginControllerText=Get-Content -Path $T_F_AdminLoginController -Encoding utf8 -Raw
  $AdminLoginControllerText = $AdminLoginControllerText -replace "_____",(StrOneToUpper $User_EntityName)
  $AdminLoginControllerText = $AdminLoginControllerText -replace "__.MinName.__",(StrOneToLower $User_EntityName)
  $AdminLoginControllerText = $AdminLoginControllerText -replace "__.PwdName.__",(StrOneToUpper $User_LogInEntiPass)
  $AdminLoginControllerText = $AdminLoginControllerText -replace "__.LoginName.__",(StrOneToUpper $User_LogInEntiCount)
  $P_F_AdminLoginController=".\src\main\java\com\yyge\controller\admin\login\AdminLoginController.java"
  $LoginControllerPath = (Get-Item -Path $P_F_AdminLoginController).FullName
  [System.IO.File]::WriteAllLines($LoginControllerPath,$AdminLoginControllerText,$encoding)

}




# 创建文件夹用于监听文件添加 主添加的监听
# 添加这个二次监听的原因是 强制对话框用的是新的线程 他无法获取外部的变量
$AddPath= $env:USERPROFILE+"\AppData\Local\CodeAG\.Data\add\"
CreateDir($AddPath)

# 多文件夹监听
#设置文件创建时的监听器
function Listener($Path){
  Write-Host "系统已经开启了监听器..."
  Write-Host $Path
  $paths = @()
  $paths+=$AddPath
  
  $paths+=(Get-Item -Path $Path).FullName
  Write-Host $AddPath
  Write-Host (Get-Item -Path $Path).FullName
  
  # 创建 FileSystemWatcher 实例并设置属性
  $watchers = foreach ($P in $paths) {
      $watcher = New-Object System.IO.FileSystemWatcher
      $watcher.Path = $P 
      $watcher.IncludeSubdirectories = $true
      $watcher.EnableRaisingEvents = $true
  
      # 添加事件处理函数
      $createdEvent = Register-ObjectEvent -InputObject $watcher -EventName Created -Action {
          $FullName  = $Event.SourceEventArgs.FullPath
          $name  = $Event.SourceEventArgs.Name

        #监听文件的新增
        if(Test-Path -PathType Leaf -Path $FullName){
          # 弹出对话框函数

            # 将多个变量拼接成字符串，用特定分隔符分割
            # 在 PowerShell 中以单线程单元模式启动脚本
            if($FullName.IndexOf("AppData\Local\CodeAG\.Data") -eq -1){
              powershell -sta -command {
                param($FullName)
  
                $name = (Get-Item -Path $FullName).Name
                Add-Type -AssemblyName System.Windows.Forms
    
                $result = [System.Windows.Forms.MessageBox]::Show(
                  "检测到可创建的实体类$name 是否创建Controller等相关文件？", 
                  "创建确认", 
                  [System.Windows.Forms.MessageBoxButtons]::YesNo, 
                  [System.Windows.Forms.MessageBoxIcon]::Question, 
                  [System.Windows.Forms.MessageBoxDefaultButton]::Button1, 
                  [System.Windows.Forms.MessageBoxOptions]::DefaultDesktopOnly -bor [System.Windows.Forms.MessageBoxOptions]::SetForeground)
                  Write-Host $result
                  # 点击确定后
                  if($result -eq "Yes"){
                    Write-Host "你点击了确定"
                    $AddCachePath= $env:USERPROFILE+"\AppData\Local\CodeAG\.Data\add\$name"
                    New-Item -ItemType File -Path $AddCachePath -Value  $FullName -Force | Out-Null
                    Write-Host "系统创建了 $AddCachePath 文件"
                    [System.IO.File]::WriteAllLines($AddCachePath,$FullName,$encoding)
                  }
              
              } -args $FullName
            }else{
              # .Data/add 文件监听事件
              Write-Host "系统监听到了 $env:USERPROFILE+\AppData\Local\CodeAG\.Data\add 文件夹内有文件创建 -949"
              # Start-Sleep -Milliseconds 100
              $BodyPath = Get-Content -Path $FullName -Encoding utf8 -Raw
              Write-Host $BodyPath
              & $Global:CreateAll $BodyPath $false
              # $OutString = $Y_EntityNameList | Out-String
              # Write-Host $OutString
            }
        }
        Write-Host "文件 $FullName  相关文件 被创建"
      }
      $watcher
  }
  
  # 持续监听
  while ($true) {
      # 保持脚本运行
      Start-Sleep -Seconds 2
  }
  
  
  
  # $deletedHandler = Register-ObjectEvent -InputObject $watcher -EventName Deleted -SourceIdentifier FileDeleted -Action {
  #     $filePath = $Event.SourceEventArgs.FullPath
  #     $changeType = $Event.SourceEventArgs.ChangeType
  #     Write-Host "文件 $filePath 被删除，类型: $changeType"
  # }
  
  # $changedHandler = Register-ObjectEvent -InputObject $watcher -EventName Changed -SourceIdentifier FileChanged -Action {
  #     $filePath = $Event.SourceEventArgs.FullPath
  #     $changeType = $Event.SourceEventArgs.ChangeType
  #     Write-Host "文件 $filePath 被修改，类型: $changeType"
  # }
  
  # $renamedHandler = Register-ObjectEvent -InputObject $watcher -EventName Renamed -SourceIdentifier FileRenamed -Action {
  #     $filePath = $Event.SourceEventArgs.FullPath
  #     $changeType = $Event.SourceEventArgs.ChangeType
  #     $oldName = $Event.SourceEventArgs.OldName
  #     $newName = $Event.SourceEventArgs.Name
  #     Write-Host "文件 $filePath 被重命名，类型: $changeType，旧名称: $oldName，新名称: $newName"
  # }

}


# 监听的是Mapper.java文件
if(Test-Path -Path $P_P_Mapper){
  # 添加监听器
  Listener $P_P_Mapper
 }else{
  CreateDir $P_P_Mapper
  # 添加监听器
  Listener $P_P_Mapper
}



# $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')

# 调用后端脚本文件
# if($Detection -ne $true){
#     & "./.temp/.script/backend.ps1"
#    }
#    $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
   #调用前端文件
  #  if($Detection -ne $true){
  #   & "./.temp/.script/foreend.ps1"
  #  }
  #  $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')

